package com.x9space.framework.elastic.handler;


import com.x9space.common.utils.StringUtils;
import com.x9space.framework.elastic.annotation.TermMatch;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

public class TermsMatchQueryHandler extends QueryHandler{
    @Override
    public String getName() {
        return "TermsMatch";
    }

    @Override
    protected QueryBuilder _doHandle(Annotation annotation, Map<String, Object> context) {
        if (!(annotation instanceof TermMatch)) {
            return null;
        }
        TermMatch item = (TermMatch) annotation;

        String field = item.field();
        if (StringUtils.isBlank(field)){
            field = ((Field)context.get("field")).getName();
        }
        Object value = context.get("value");

        Class<?> clazz = value.getClass();
        Class<?> componentType = clazz.getComponentType();

        if (componentType!= null){
            Object[] array = (Object[]) value;
            return QueryBuilders.termsQuery(field,array);
        } else if (value instanceof Iterable){
            Iterable iterable = (Iterable) value;
            Iterator iterator = iterable.iterator();
            ArrayList<Object> list = new ArrayList<>();
            while (iterator.hasNext()) {
                list.add(iterator.next());
            }
            return QueryBuilders.termsQuery(field,list);
        } else {
            if (value instanceof String){
                String str = (String) value;
                String[] split = str.split(",");
                return QueryBuilders.termsQuery(field,split);
            }
        }
        return null;
    }
}
